<template>
  <div class="card-box">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="100px"
      class="form__content"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="审批意见" prop="remarks">
            <ReFastInput @emitFastInput="emitFastInput" />
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model.trim="formData.remarks"
            ></el-input>
            <span>请确认项目、合同及到货信息。</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form__footer">
      <!-- <el-button type="primary" @click="handleSave">保 存</el-button> -->
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
      <el-button type="primary" @click="handleTransfer">转 办</el-button>
      <!-- <el-button type="primary" @click="handleReject">驳 回</el-button> -->
    </div>

    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view
        v-model:dialogVisible="dialogVisible"
        :taskId="props.taskId"
      />
    </el-dialog>

    <el-dialog
      title="转办"
      v-model="dialogVisibleTransfer"
      destroy-on-close
      width="820px"
    >
      <transfer-view
        v-model:dialogVisibleTransfer="dialogVisibleTransfer"
        :taskId="props.taskId"
      />
    </el-dialog>
    <el-dialog
      title="返回发货通知回执"
      v-model="commitVisible"
      destroy-on-close
      width="600px"
    >
      <div class="dialog__content">
        <div class="dialog__content--title">确认将审批意见发送至:</div>
        <el-row>
          <el-col :span="3" class="col-left"></el-col>
          <el-col :span="21" class="col-right">{{
            currentTeam.userName
          }}</el-col>
        </el-row>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commitVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="handleRequest">确认</el-button> -->
          <ReButton type="primary" debounce auto-loading @click="handleRequest"
            >确认</ReButton
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ReFastInput from "/@/components/ReFastInput/index.vue";
import { reactive, ref, watch, defineProps, onMounted, nextTick } from "vue";
import {
  postNoticeRcpSubmit,
  postGetStorageTmpData
  // postArrivalAccReject,
  // postChangeAssignee
} from "/@/api/acceptance";
import { useRouter, useRoute } from "vue-router";
import RejectView from "../dialog/RejectView.vue";
import TransferView from "../dialog/TransferView.vue";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";

import ReButton from "/@/components/ReButton/index.vue";

// import { ElMessageBox } from "element-plus";

const props = defineProps({
  storageData: {
    type: Object,
    default: () => {}
  },
  taskId: {
    type: String,
    default: ""
  },
  projectTeam: {
    type: Array,
    default: () => []
  }
});

// 获取合同对应的负责人
let directorObj = reactive({
  directorA: "",
  directorBId: ""
});

let currentTeam = reactive({
  userName: "",
  userId: ""
}); // 下一节点的处理人信息

let commitVisible = ref<boolean>(false);
const formRef = ref<HTMLFormElement | null>(null) as any;
const formData = reactive({
  remarks: ""
});
let dialogVisible = ref<boolean>(false);
let dialogVisibleTransfer = ref<boolean>(false);
const router = useRouter();
const route = useRoute();

let outterId = ref(null);
let effective = ref(null);

const formRules = {
  remarks: { required: true, message: "请填写审批意见", trigger: "change" }
};

if (props.storageData?.directorA) {
  directorObj = {
    directorA: props.storageData.directorA,
    directorBId: props.storageData.directorBId
  };
}

// 确认下以下代码是否有必要
watch(
  () => props.storageData,
  newVal => {
    directorObj.directorA = newVal.directorA;
    directorObj.directorBId = newVal.directorBId;
    console.log(directorObj, "directorObj");
  }
);

const handleSubmit = async () => {
  try {
    const isValid = await new Promise(resolve =>
      formRef.value.validate(resolve)
    );
    if (!isValid) return;
    commitVisible.value = true;
    props.projectTeam.forEach(item => {
      if ((item as any)?.roleCode === "4") {
        currentTeam.userName = (item as any)?.userName;
        currentTeam.userId = (item as any)?.userId;
      }
    });
  } catch (err) {
    console.log(err);
  }
};

const handleRequest = async done => {
  try {
    const { instanceId, nodeDefId, flowId } = route.query;
    const info = storageLocal.getItem("info");
    let params = {
      formSubMap: {
        nodeId: nodeDefId,
        isAllAcceptance: "",
        procInstId: instanceId,
        taskId: props.taskId,
        opinion: `审批意见：${formData.remarks}`,
        assignee: currentTeam.userId // 提交下一流程处理人Id
      },
      tmpStorage: {
        nodeId: nodeDefId,
        flowId,
        taskId: props.taskId,
        handlerId: info?.userId ?? "",
        userId: info?.userId ?? "",
        valueJson: JSON.stringify({
          ...formData,
          flowInfoId: flowId
        })
      }
    };

    // 根据后端要求。传一个outterId
    if (outterId.value) {
      const joinData = Object.assign(params.tmpStorage, {
        outterId: outterId.value
      });
      params.tmpStorage = joinData;
    }
    // 根据后端要求。传一个effective
    if (effective.value) {
      const joinData = Object.assign(params.tmpStorage, {
        effective: effective.value
      });
      params.tmpStorage = joinData;
    }
    const { code } = await postNoticeRcpSubmit(params);
    if (code === 200) {
      commitVisible.value = false;
      NotifMessage.success("提交成功");
      // router.replace("/acceptance/arrival");
      handleBack();
    }
  } catch (err) {
    console.log(err);
  } finally {
    setTimeout(() => {
      done();
    }, 1000);
  }
};

// const handleReject = () => {
//   dialogVisible.value = true;
// };

const getStorageTmpData = async () => {
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : ""
  };

  const { code, data } = await postGetStorageTmpData(params);
  if (code === 200) {
    if (data?.valueJson) {
      const { remarks } = JSON.parse(data.valueJson);
      formData.remarks = remarks;
      outterId.value = data.outterId;
      effective.value = data?.effective ?? "";
    }
  }
};

onMounted(() => {
  nextTick(() => {
    getStorageTmpData();
  });
});

const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/acceptance/arrival", replace: true });
  }
};

const handleTransfer = async () => {
  dialogVisibleTransfer.value = true;
};

// 快速输入
const emitFastInput = tag => {
  formData.remarks = `${formData.remarks}${tag}`;
};
</script>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .form__content {
    flex: 1;
    width: inherit;
  }
  .form__footer {
    width: inherit;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.dialog__content {
  border: 1px solid #f0f4ff;
  border-radius: 4px;

  &--title {
    background: #f0f4ff;
    font-size: 16px;
    padding: 4px 8px;
  }
  .el-row {
    padding: 4px;
  }
  .col-left {
    text-align: right;
  }
  .col-right {
  }
}
</style>
